from datetime import datetime, timedelta
from peewee import *
from typing import Optional

from common.enum.form_items_key import FormItemsKey
from common.enum.operation_log_type_enum import LogType
from .database_pool import DatabasePool

db = DatabasePool()


class OperationLog(Model):
    # 执行时间
    execution_time = DateTimeField(default=datetime.now)
    # 执行类型
    execution_type = CharField(max_length=100)
    # 执行内容
    execution_content = TextField()
    # 执行模块
    execution_module = CharField(max_length=100)
    # 创建时间
    create_time = DateTimeField(default=datetime.now)
    # 更新时间
    update_time = DateTimeField(default=datetime.now)

    class Meta:
        database = db.database
        table_name = "automation_operation_log"


class OperationLogDas:
    # 添加日志记录
    def add_log(
        self,
        execution_type: str,
        execution_content: str,
        execution_module: str,
        execution_time: Optional[datetime] = None,
    ):
        try:
            log = OperationLog.create(
                execution_time=execution_time or datetime.now(),
                execution_type=execution_type,
                execution_content=execution_content,
                execution_module=execution_module,
                create_time=datetime.now(),
                update_time=datetime.now(),
            )
            AntLogger.info(f"日志记录已添加成功，ID: {log.id}")
        except Exception as e:
            AntLogger.info(f"添加日志记录失败: {e}")

    # 查询所有日志
    def get_all_logs(self):
        logs = OperationLog.select()
        return list(logs)

    # 根据执行类型查询日志
    def get_logs_by_type(self, execution_type: str):
        try:
            logs = OperationLog.select().where(
                OperationLog.execution_type == execution_type
            )
            return list(logs)
        except Exception as e:
            AntLogger.info(f"查询日志时发生错误: {e}")
            return []

    # 根据执行模块查询日志
    def get_logs_by_module(self, execution_module: str):
        try:
            logs = OperationLog.select().where(
                OperationLog.execution_module == execution_module
            )
            return list(logs)
        except Exception as e:
            AntLogger.info(f"查询日志时发生错误: {e}")
            return []

        # 查询最后一次“全局计算”类型的执行时间

    def get_last_global_computation_time(self, logType: LogType) -> Optional[datetime]:
        try:
            last_log = (
                OperationLog.select()
                .where(OperationLog.execution_type == logType.value)
                .order_by(OperationLog.execution_time.desc())
                .first()
            )

            return last_log.execution_time if last_log else None
        except Exception as e:
            AntLogger.info(f"查询最后一次执行时间时发生错误: {e}")
            return None

    # 判断是否满足条件
    def should_perform_action(
        self, logType: LogType, time_diff_limit: int, hour_limit: int
    ) -> bool:
        # 获取最后一次执行的时间
        last_exec_time = self.get_last_global_computation_time(logType)

        if last_exec_time is None:
            AntLogger.info("没有找到任何全局计算日志记录。")
            return True

        # 当前时间
        current_time = datetime.now()

        # 判断是否距离最后执行小于传入的时间差
        time_diff = current_time - last_exec_time
        if time_diff < timedelta(hours=time_diff_limit):
            AntLogger.info
                f"最后一次执行时间距离当前时间小于 {time_diff_limit} 小时，返回 False。"
            )
            return False

        # 判断是否在传入的小时之前
        if current_time.hour < hour_limit:
            AntLogger.info(f"当前时间在 {hour_limit} 点之前，返回 False。")
            return False

        # 如果以上条件都不满足，返回 True
        AntLogger.info("可以继续执行操作，返回 True。")
        return True
